//
//  TakePhotoViewController.m
//  TakePhotoDemo
//
//  Created by YangShuai on 16/8/31.
//  Copyright © 2016年 ys. All rights reserved.
//

#import "TakePhotoViewController.h"
#import "ConstDefine.h"
@interface TakePhotoViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic,strong) UIView *containView;
@property (nonatomic,strong) UIView *captureView;
@property (nonatomic,strong) UIButton *toggleButton;
@property (nonatomic,strong) UIButton *shotButton;
@property (nonatomic,strong) UIView *slideUpView;
@property (nonatomic,strong) UIView *slideDownView;
@property (nonatomic,strong) YSCameraManager *camera;
@property (nonatomic,assign) BOOL wasLoaded;
//
@property (nonatomic,strong) UIImageView *activityImageView;;
@end

@implementation TakePhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [DataProcessing shareSingle].souvenirExist = YES;
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F0F1F5"];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 56)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = NSLocalizedString(@"photoFinish", "");
    titleLabel.font = [UIFont boldSystemFontOfSize:22];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPad) {
        self.naviBar = [JRNaviBar getJRNaviBarWithSuperView:self.contentView centerView:titleLabel leftViews:nil rightViews:nil];
    }else{
        titleLabel.frame = CGRectMake(0, 0, 200, 25);
        titleLabel.font = [UIFont boldSystemFontOfSize:15];
        self.naviBar = [JRNaviBar getJRNaviBarWithSuperView:self.contentView centerView:titleLabel leftViews:nil rightViews:nil];
    }
    [self addBackView];
    
    [self viewsLayout];
    
    //
    _camera = [YSCameraManager cameraWithFlashButton:nil];
    [_camera toogleWithFlashButton:nil];
    _captureView.backgroundColor = [UIColor clearColor];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(deviceOrientationDidChangeNotification)
//                                                 name:UIDeviceOrientationDidChangeNotification
//                                               object:nil];
    [_camera startRunning];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    //[self deviceOrientationDidChangeNotification];
    
    if (_wasLoaded == NO) {
        _wasLoaded = YES;
        [_camera insertSublayerWithCaptureView:_captureView atRootView:_containView];
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [_camera stopRunning];
}

-(void)viewsLayout{
    //containView
    self.containView = [[UIView alloc] init];
    self.containView.backgroundColor = [UIColor colorWithHexString:@"#B2ABDD"];
    [self.view addSubview:_containView];
    [_containView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(130);
        make.right.JRMAS_equalTo(-130);
        make.top.JRMAS_equalTo(90);
        make.height.JRMAS_equalTo(568);
    }];
    
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        [_containView JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
            make.left.JRMAS_equalTo(35);
            make.right.JRMAS_equalTo(-35);
            make.top.JRMAS_equalTo(90);
            make.height.JRMAS_equalTo(_containView.JRMAS_width).multipliedBy(1.12);
        }];
    }
    
    //成像区域
    self.captureView = [[UIView alloc] init];
    _captureView.backgroundColor = [UIColor lightGrayColor];
    [_containView addSubview:_captureView];
    [_captureView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(4 / ratio_w);
        make.right.JRMAS_equalTo(-4 / ratio_w);
        make.top.JRMAS_equalTo(4 / ratio_w);
        make.height.JRMAS_equalTo(_captureView.JRMAS_width).multipliedBy(1);
    }];
    //精灵动画
    self.activityImageView = [[UIImageView alloc] init];
    self.activityImageView.image = [self.spritImageArray firstObject];
    if (self.spritImageArray.count > 0) {
        _activityImageView.animationImages = self.spritImageArray;
        _activityImageView.animationDuration = 1;
        _activityImageView.animationRepeatCount = 0;
        [_activityImageView startAnimating];
    }
    [_captureView addSubview:self.activityImageView];
    [self.activityImageView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.JRMAS_equalTo(0);
    }];
    //摄像头变化按钮
    self.toggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_toggleButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.toggleButton addTarget:self action:@selector(tapToggle:) forControlEvents:UIControlEventTouchUpInside];
    [self.toggleButton setImage:[UIImage imageNamed:@"btn_reverse_camera.png"] forState:UIControlStateNormal];
    _toggleButton.adjustsImageWhenHighlighted = NO;
    [_toggleButton addTouchScaleTransitions];
    [_containView addSubview:_toggleButton];
    [_toggleButton JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.top.JRMAS_equalTo(_captureView.JRMAS_bottom).offset(4);
        make.height.JRMAS_equalTo(60 / ratio_w);
        make.centerX.JRMAS_equalTo(0);
    }];
    //拍照button
    self.shotButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shotButton addTarget: self action:@selector(tapShot:) forControlEvents:UIControlEventTouchUpInside];
    [self.shotButton setImage:[UIImage imageNamed:@"btn_camera.png"] forState:UIControlStateNormal];
    _shotButton.adjustsImageWhenHighlighted = NO;
    [_shotButton addTouchScaleTransitions];
    [_shotButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:_shotButton];
    [_shotButton JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.bottom.JRMAS_equalTo(-50);
        make.centerX.JRMAS_equalTo(0);
    }];
}

-(void)reflashSpritImageAni{
    if (self.spritImageArray.count > 0) {
        _activityImageView.animationImages = self.spritImageArray;
        _activityImageView.animationDuration = 1;
        _activityImageView.animationRepeatCount = 0;
        [_activityImageView startAnimating];
    }
}

-(void)tapBack{
    [DataProcessing shareSingle].souvenirExist = NO;
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -
#pragma mark - Actions
-(void)tapToggle:(UIButton*)button{
    [_camera toogleWithFlashButton:nil];
}

-(void)tapShot:(UIButton*)button{
    _shotButton.enabled = NO;
//    UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
//    AVCaptureVideoOrientation videoOrientation = [self videoOrientationForDeviceOrientation:deviceOrientation];
    AVCaptureDevicePosition position = [_camera getDevicePosition];
    [_camera takePhotoWithCaptureView:_captureView effectiveScale:1 videoOrientation:AVCaptureVideoOrientationPortrait completion:^(UIImage *photo) {
        HandlePhotoViewController *viewController = [[HandlePhotoViewController alloc] init];
        if (position == AVCaptureDevicePositionFront) {
            viewController.isCameraFront = YES;
        }else{
            viewController.isCameraFront = NO;
        }
        viewController.funcPage = self.funcPage;
        viewController.bookCoverImage = _bookCoverImage;
        viewController.bookid = _bookid;
        viewController.photo = photo;
        viewController.sourceUrlsDict = self.sourceUrlsDict;
        viewController.spiritImage = [self arcRomdomPhotoImage];
        viewController.hurdleNo = _hurdleNo;
        viewController.activityId = _activityId;
        viewController.bookName = _bookName;
        [self.navigationController pushViewController:viewController animated:YES];
        _shotButton.enabled = YES;
    }];
    //阅读统计
    [[DBHelper shareInstance] addReadInfo_bookReadMode:self.bookid mode:RMode_photo];
}
//
-(UIImage *)arcRomdomPhotoImage{
    UIImage* image = [self.spritImageArray firstObject];
    NSInteger imageIndex = arc4random() % 3;
    if (self.spritImageArray.count > imageIndex) {
        image = [self.spritImageArray objectAtIndex:imageIndex];
    }
    return image;
}
//
-(void)clearTapped{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -
#pragma mark - Private methods

- (void)deviceOrientationDidChangeNotification
{
    UIDeviceOrientation orientation = [UIDevice.currentDevice orientation];
    NSInteger degress;
    
    switch (orientation) {
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationPortrait:
        case UIDeviceOrientationUnknown:
            degress = 0;
            break;
            
        case UIDeviceOrientationLandscapeLeft:
            degress = 90;
            break;
            
        case UIDeviceOrientationFaceDown:
        case UIDeviceOrientationPortraitUpsideDown:
            degress = 180;
            break;
            
        case UIDeviceOrientationLandscapeRight:
            degress = 270;
            break;
    }
    
    CGFloat radians = degress * M_PI / 180;
    CGAffineTransform transform = CGAffineTransformMakeRotation(radians);
    
    [UIView animateWithDuration:.5f animations:^{
        _toggleButton.transform = transform;
    }];
}

- (AVCaptureVideoOrientation)videoOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    AVCaptureVideoOrientation result = (AVCaptureVideoOrientation) deviceOrientation;
    
    switch (deviceOrientation) {
        case UIDeviceOrientationLandscapeLeft:
            result = AVCaptureVideoOrientationLandscapeRight;
            break;
            
        case UIDeviceOrientationLandscapeRight:
            result = AVCaptureVideoOrientationLandscapeLeft;
            break;
            
        default:
            break;
    }
    
    return result;
}

@end
